import router from './router'
import $store from '@/common/store/_store'
import $http from '@/common/util/http'
import $kit from '@/common/util/Kit'
import NProgress from 'nprogress'

//白名单路由
let publicRouter = ['/public/serverStop', '/public/login']

NProgress.configure({showSpinner: false});

router.beforeEach(async (to, from, next) => {
    NProgress.start()

    //放行
    if (publicRouter.indexOf(to.path) != -1) {
        next()
    }

    //检查
    else {

        //检查首次登录
        let status = firstLogin(to, from, next);
        if (status == true) return;

        //判断页面刷新
        if ($store.state.refresh) {
            ////console.log("页面刷新")

            //查用户信息
            await $http.post('/system/user/loginUserInfo', {}).then((res) => {
                $store.state.userInfo = res.data
                localStorage.setItem("userId", $store.state.userInfo.id)
            })

            //查菜单
            await $http.post('/system/user/menu', {}).then((res) => {
                $store.state.routerOrigin = res.data
                $store.state.router = $kit.getTree(res.data)
                ////console.log($store.state.router)
            })

            $store.state.refresh = false
        }

        //放行
        next()
    }
})

router.afterEach(() => {
    NProgress.done() // start progress bar
})

//首次登录拦截
let firstLogin = (to, from, next) => {
    let token = localStorage.getItem("Token");
    let refreshToken = localStorage.getItem("refreshToken");
    if (!token || !refreshToken) {
        ////console.log("checkLogin-未登录")
        //携带路径
        next(`/public/login?redirect=${to.path}`);
        return true;
    }
    return false;
}

